package org.lzuploader.gui.listeners.servers;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Shell;
import org.lzuploader.gui.WServers;
import org.lzuploader.model.Config;
import org.lzuploader.model.Server;

/** This class is used when user clicks on the server list.
 * 
 * @author Emmanuel Cron
 *
 */
public class ListSelectionListener implements SelectionListener
{
    /** The logger for this class. */
    private static Log log = LogFactory.getLog(ListSelectionListener.class);
    
    /** Used when the widget is selected by default.
     * @param e The associated event
     */
    @Override
    public void widgetDefaultSelected(final SelectionEvent e)
    {
        widgetSelected(e);

    }

    /** Used when the user clicked on the widget.
     * @param e The associated event
     */
    @Override
    public void widgetSelected(final SelectionEvent e)
    {
        log.debug("User selected list.");
        
        log.trace("Fetching data.");
        
        Shell wServersShell = null;
        for (int i = 0 ; i < e.display.getShells().length ; i++)
        {
            if (e.display.getShells()[i].getData() instanceof WServers)
            {
                wServersShell = e.display.getShells()[i];
                break;
            }
        }
        
        final WServers servers = (WServers) wServersShell.getData();
        final List list = servers.getList();
        final int currentSelection = list.getSelectionIndex();
        
        log.trace("Checking if there is a selected server.");
        
        if (currentSelection >= 0)
        {
            final String serverId = list.getItem(currentSelection);
            final Config config = Config.getInstance();
            final Server server = config.getServers().get(servers.getList().getSelection()[0]);
            
            log.trace("Currently selected: " + serverId.toString() + " (" + currentSelection + ")");
            log.trace("Populating controls.");
            
            servers.getNameWidget().setText(server.getId());
            servers.getServerWidget().setText(server.getAddress());
            servers.getPortWidget().setSelection(server.getPort());
            servers.getPathWidget().setText(server.getPath());
            
            if (servers.getRemoveButton().getEnabled() == false)
            {
                log.trace("Enabling remove server button.");
                
                servers.getRemoveButton().setEnabled(true);
            }
        }
    }

}
